<?php

namespace Models;

use OAuth2\ResponseType\AccessToken;
use OAuth2\Storage\Redis;
use ReflectionClass;

/**
 * 用户模型
 * @package Models
 * @author suntianxiang<suntianxiang@sina.cn>
 */
class User extends Model{

	protected $_table = 'users';

	protected $_filter = FALSE;

	protected $_primekey = 'id';

	protected $_belongs = [
		'level' => [
			'class' => UserLevel::Class,
			'foreign' => 'id',
			'belongs_key' => 'level',
		],
		'cashier' => [
			'class' => Cashier::Class,
			'foreign' => 'id',
			'belongs_key' => 'cashier_id',
		],
	];

	public function verify($password)
	{
		if (password_verify($password, $this['password'])) {
			if (password_needs_rehash($this['password'], PASSWORD_DEFAULT)) {
				$newHash = password_hash($password, PASSWORD_DEFAULT);
				$this->update($this['id'], [
					'password' => $newHash
				]);
			}

			return true;
		} else {
			return false;
		}
	}

	public function CreateSystemAccessToken($scope = null)
	{
		$twoHours = 7200;
		$twoWeek = 86400*2;
		$storage = new Redis(predis());
		$client = OAuth2Client::where('client_id', 'system')->get_one();

		$reflectClass = new ReflectionClass(AccessToken::Class);
		$accessToken = $reflectClass->newInstanceWithoutConstructor();
		$method = $reflectClass->getMethod('generateAccessToken');
		$method->setAccessible(true);
		$access_token = $method->invoke($accessToken);

		$storage->setAccessToken($access_token, $client['client_id'], $this['id'], time() + $twoHours, $scope);

		$refresh_token = $method->invoke($accessToken);
		$storage->setRefreshToken($refresh_token, $client['client_id'], $this['id'], time() + $twoWeek, $scope);

		return [
			'access_token' => $access_token,
			'expires_in' => $twoHours,
			'token_type' => 'bearer',
			'scope' => $scope,
			'refresh_token' => $refresh_token,
			'refresh_token_expires_in' => $twoWeek
		];
	}

	public function login()
	{
		$this['login_at'] = date('Y-m-d H:i:s');
	}

	/**
	 * 在消费后需要升级吗？
	 *
	 * @return bool 是否升级了
	 */
	public function levelUpIfNeed($money)
	{
		//查找用户充值总金额
		$total = Money_log::select_sum('num')->where('user_id',$this['id'])->where('num > 0')->get_one();
		//查找用户等级
		$user_level = UserLevel::where('credits <=',($total['num']+$money))->order_by('credits','desc')->get_one();
		if($user_level){
			$this['level'] = $user_level['id'];
			$this->update($this['id'], [
				'level' => $user_level['id']
			]);

			return true;
		}

		return false;
	}
}
?>
